package com.dhq.myapp.util

import android.content.res.Resources
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import androidx.recyclerview.widget.RecyclerView
import android.util.SparseArray

/**
 * DESC RecycleView的公用ViewHolder
 * Created by admin on 2016/9/7.
 */
class CustomHeaderHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    /**
     * save view ids
     */
    private val mSparseArray: SparseArray<View> = SparseArray()
    private val rootView: View = itemView

    /**
     * 获取跟布局
     */
    fun getRootView(): View {
        return rootView
    }

    /**
     * 根据id获取控件
     */
    fun <T : View> getView(resId: Int): T {
        var view = mSparseArray[resId]
        if (view == null) {
            view = rootView.findViewById(resId)
            mSparseArray.put(resId, view)
        }
        @Suppress("UNCHECKED_CAST")
        return view as T
    }

    fun setText(id: Int, str: String): CustomHeaderHolder {
        val view = getView<View>(id)
        if (view is TextView) {
            view.text = str
        }
        return this
    }

    fun setText(@IdRes id: Int, @StringRes strId: Int, vararg str: Any?): CustomHeaderHolder {
        val view = getView<View>(id)
        val resources: Resources = view.context.resources
        val formatStr = String.format(resources.getString(strId), *str)
        if (view is TextView) {
            view.text = formatStr
        }
        return this
    }

    fun setImg(id: Int, imgUrl: String): CustomHeaderHolder {
        val view = getView<View>(id)
        if (view is ImageView) {
//            GlideImageLoadUtils.loadImage(view, imgUrl)
        }
        return this
    }
}